import asyncio
from asyncio import Future, Task, Semaphore
from typing import Final, Set, Coroutine


class TaskManager:
    def __init__(self,total_concurrency=16):
        self.semaphore:Semaphore = Semaphore(total_concurrency) # 控制并发量
        self.current_task: Final[Set] = set()

    def create_task(self, coroutine: Coroutine) -> Task:
        task = asyncio.create_task(coroutine)
        self.current_task.add(task)

        # 删除task
        def done_callback(_fut: Future):
            self.current_task.remove(task)
            self.semaphore.release()

        task.add_done_callback(done_callback)
        return task

    def all_done(self) -> bool:

        return len(self.current_task) == 0